package cn.tedu._07weibo.base.exception;


import cn.tedu._07weibo.base.response.JsonResult;
import cn.tedu._07weibo.base.response.StatusCode;
import jakarta.validation.ConstraintViolationException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

@Slf4j
@RestControllerAdvice //ResponseBody,和 ControllerAdvice
public class GlobalExceptionHandler {
    @ExceptionHandler(IllegalArgumentException.class)
    public JsonResult doHandleIllegalArgumentException(IllegalArgumentException ex){

        String data = ex.getMessage();
        return new JsonResult(StatusCode.OPERATION_FAILED,data);


    }
//    @ExceptionHandler(RuntimeException.class)
//    public JsonResult doHandleRuntimeException(RuntimeException ex){
//        log.error("父类运行时异常："+ex.getMessage());
//        String data=ex.getMessage();
//        return new JsonResult(StatusCode.OPERATION_FAILED,data);
//    }
//    //能够处理所有异常的异常处理方法
//    @ExceptionHandler(Throwable.class)
//    public JsonResult doHandleThrowable(Throwable ex){
//        log.error("全局异常："+ex.getMessage());
//        String data=ex.getMessage();
//        return new JsonResult(StatusCode.THROWABLE_ERROR,data);
//    }
    @ExceptionHandler(MethodArgumentNotValidException.class)
    public JsonResult doHandlerMethodArgumentNotValidException(MethodArgumentNotValidException ex){
        String data=ex.getFieldError().getDefaultMessage();
        log.error("参数验证失败："+data);
        return new JsonResult(StatusCode.VALIDATED_ERROR,data);

    }
    @ExceptionHandler(ConstraintViolationException.class)
    public JsonResult doHandlerConstraintViolationException(ConstraintViolationException ex){
        String data=ex.getMessage().split(": ")[1].trim();
        log.error("ConstraintViolationException"+data);
        return new JsonResult(StatusCode.VALIDATED_ERROR,data);
    }



}
